<!--
 * @Descripttion: 下载图片
 * @version:
 * @Author: lehaixia
 * @Date: 2021-10-25 15:46:16
 * @LastEditors: lehaixia
 * @LastEditTime: 2021-10-27 10:09:09
-->
<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="600px"
    :before-close="closeDialog"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-form ref="refForm" :rules="formRules" :model="formData" size="mini" label-width="100px">
      <el-form-item label="文件名:" prop="fileName">
        <el-input
          v-model="formData.fileName"
          placeholder="请输入下载后下载保存的文件名称"
          maxlength="50"
          style="width:100%"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="closeDialog">取 消</el-button>
      <el-button type="primary" size="mini" @click="handleSure">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { exportDataToFile } from '@/api/serviceQuality'
export default {
  name: 'ExportImage',
  components: { },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '下载数据'
    },
    downloadUrl: {
      type: String,
      default: ''
    }, // 离线下载任务接口地址
    config: {
      required: true,
      type: Array,
      default: () => {
        return [
          {
            code: '', // 下载模板的编码(前端自定义提供)
            name: '', // 下载模板的名称(前端自定义或需产品提供)
            dataApi: '', // 下载数据的地址(后端提供)
            selectedRows: [], // 选中行(用于指定行下载)
            queryField: [] // 选中行下载的查询字段名称(selectedRows不为空时，此字段必填)
          }
        ]
      }
    }
  },
  data() {
    return {
      formData: {
        fileName: ''
      },
      formRules: {
        fileName: [
          { required: true, message: '请输入下载后下载保存的文件名称', trigger: ['blur', 'change'] }
        ]
      },
      dataConfig: [] // 数据下载配置
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    // 当前下载配置
    activeConfig() {
      return (this.config && this.config[0]) || ''
    }
  },
  watch: {
  },
  created() {

  },

  methods: {
    closeDialog() {
      this.dialogVisible = false
      this.$refs.refForm && this.$refs.refForm.clearValidate()
      this.clearForm()
    },
    clearForm() {
      this.$set(this.formData, 'fileName', '')
    },
    // 确定下载
    handleSure() {
      if (this.submiting) return
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          const fileName = this.formData.fileName

          if (this.activeConfig.selectedRows.length === 0) {
            this.$message.warning('请先选择需要下载的数据行')
            return
          }

          this.exportTableData(fileName)
        }
      })
    },
    // 下载数据
    exportTableData(fileName) {
      const activeConfig = JSON.parse(JSON.stringify(this.activeConfig))
      const {
        dataApi,
        selectedRows = [],
        queryField = []
      } = activeConfig

      if (!dataApi) {
        this.$message.warning('下载数据参数配置异常')
        return
      }

      const filterValues = [] // 最后需传递的数据
      selectedRows.forEach(v => {
        const item = {}
        queryField.forEach(i => {
          return Object.assign(item, { [i]: v[i] })
        })
        filterValues.push(item)
      })

      this.submiting = true
      const loading = this.$loading({
        lock: true,
        text: '正在下载数据,请耐心等待',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.2)',
        customClass: 'custom-loading'
      })
      exportDataToFile(dataApi, 'post', filterValues, fileName).then(res => {
        if (!res || res.type === 'application/zip') {
          this.$message.warning('数据下载失败')
          this.submiting = false
          loading.close()
          return
        }

        this.createDownload(res.data, fileName)
        this.$message.success('数据下载成功,正在下载')

        this.submiting = false
        loading.close()
        this.dialogVisible = false
        this.clearForm()
        this.$emit('success')
      }).catch((err) => {
        console.log(err)
        this.$message.warning('下载失败')
        this.submiting = false
        loading.close()
      })
    },
    /**
     * 创建下载
     * @param {blob} data 文件流
     * @param {string} fileName  文件名称
     * */
    createDownload(data, fileName) {
      if (!data) return
      if (fileName) {
        fileName = `${decodeURIComponent(fileName)}.zip`
      } else {
        fileName = data.headers['content-disposition']
        fileName = fileName.split(';')[1].split('filename=')[1]
        const fileNameUnicode = data.headers['content-disposition'].split('filename*=')[1]
        if (fileNameUnicode) { // 当存在 filename* 时，取filename* 并进行解码（为了解决中文乱码问题）
          fileName = decodeURIComponent(fileNameUnicode.split("''")[1])
        } else {
          fileName = decodeURIComponent(fileName)
        }
      }

      const blob = new Blob([data], { type: 'application/zip' })
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName)
      } else {
        const link = document.createElement('a')
        const objectURL = URL.createObjectURL(blob)
        link.download = decodeURI(fileName)
        link.href = objectURL
        document.body.appendChild(link)
        link.click()
        window.URL.revokeObjectURL(objectURL)
        document.body.removeChild(link)
      }
    }
  }
}
</script>
<style lang='scss' scoped>
/* @import url(); 引入css类 */
</style>
